import { Injectable, Inject } from '@angular/core';
import { Http, Headers, RequestOptions } from "@angular/http";
import { AppService } from "app/services";

const ServerUrl = "http://localhost:54926/";
export class PageData {
  public columns: string = "";
  public limit: number = 10;
  public offset: number = 0;
  public pagenum: number = 1;
  public order: string = "desc";
  public sortby: string = "Id";
  public query: string = "";
}
@Injectable()
export class AdminService {
  private options: RequestOptions;
  ServerUrl: string = ServerUrl;
  constructor(private http: Http, private appServ: AppService) {
    this.options = new RequestOptions();
    this.options.headers = new Headers({ 'Content-Type': 'application/json' });

    //处理跨域问题
    let _build = (<any>http)._backend._browserXHR.build;
    (<any>http)._backend._browserXHR.build = () => {
      let _xhr = _build();
      _xhr.withCredentials = true;
      return _xhr;
    };
  }
  //错误处理
  private handleError(error: any): Promise<any> {
    //this.appServ.showToaster("访问服务器失败!", "系统错误", "error");
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
  //用户登录
  login(data: any): Promise<any> {
    var url = ServerUrl + "api/Login/PostLogin";
    return this.http.post(url, data, this.options)
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }
  //获取登录用户
  GetLoginUser(): Promise<any> {
    var url = ServerUrl + "api/Login/GetLoginUser";
    return this.http.get(url)
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }
  //获取权限菜单
  GetCategoryList(): Promise<any> {
    var url = ServerUrl + "api/GgcmsCategories/GetList";
    return this.http.get(url)
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }
  //获取权限菜单
  GgcmsPowersList(): Promise<any> {
    var url = ServerUrl + "api/GgcmsPowers/GetList";
    var pdata = new PageData();
    pdata.query = "PowerType:0";
    pdata.sortby = "OrderId";
    pdata.order = "asc";
    pdata.limit = 1000;
    pdata.columns = "Id,PowerName,OrderId,ParentId,PowerTag,IconClass,ShowInSidebar,PowerType,PowerParams,Path";
    var params = this.appServ.objectToParams(pdata);
    return this.http.get(url, {
      search: params
    })
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }
}
